<script>
  import $ from '../dfish.js'
  import {
    h
  } from 'vue'
  import TD from './TableTD.vue'
  import Horizontal from './Horizontal.vue'

  export default {
    name: 'w-th',
    mixins: [TD],
    props: ['sortable'],
    inject: ['thead'],
    emits: ['click:sort'],
    methods: {
      clickSort(e, order) {
        let key = this.$.vnode.key
        let sort = this.thead.sort || false
        if (key == null || key == '') return
        if (order === 'toggle') {
          if (sort.key == key) {
            order = sort.order == 'asc' ? 'desc' : sort.order == 'desc' ? '' : 'asc'
          } else {
            order = 'asc'
          }
        } else {
          if (sort.order == order) order = ''
        }
        this.$emit('click:sort', e, {key, order})
      },
      html_slots() {
        return h(Horizontal, {class: 'w-th-wrap', valign: 'middle', align: this.align || this.col.align}, {default: () => [
          h('div', {class: 'w-th-title', onClick: this.sortable && (e => this.clickSort(e, 'toggle'))}, this.$slots),
          this.sortable ? h('div', {class: 'w-th-sort f-flex-column f-flex-center f-oh'}, [
            h('i', {class: 'f-i f-i-caret-up f-oh w-th-sort-up', onClick: e => this.clickSort(e, 'asc')}),
            h('i', {class: 'f-i f-i-caret-down f-oh w-th-sort-down', onClick: e => this.clickSort(e, 'desc')}),
          ]) : []
        ]})
      }
    },
    computed: {
      col() {
        return this.table.colgroup[this.$.vnode.dfishColIndex] || false
      }
    },
    render() {
      let col = this.col
      let colspan = this.colspan
      if (colspan == -1) {
        colspan = this.table.colgroup.length
      }
      let fixed = this.table.fixed
      let sort = this.thead.sort || false
      return h('th', {
        class: ['w-td w-th', {[`z-${sort.order}`]: this.sortable && sort.key && sort.key == this.$.vnode.key}, this.provideInBody && col.class, {'f-form-hide': fixed ? col.fixed != fixed : col.fixed}],
        style: this.provideInBody && col.style,
        colspan,
        rowspan: this.rowspan,
        align: this.align || col.align,
        valign: this.valign || col.valign,
      }, this.html_slots())
    }

  }
</script>
